package com.practice.misc;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class MergeRange {

	public static void main(String[] args) {
		MergeRange mr = new MergeRange();
		mr.run();
	}
	
	private void run() {
		ArrayList<Node> list = new ArrayList<Node>();
		list.add(new Node(3, 5));
		list.add(new Node(7, 10));
		list.add(new Node(19, 21));
		list.add(new Node(23, 25));
		
		merge(list, new Node(10, 24));
	}
	
	private void merge(List<Node> list, Node newNode) {
		Iterator<Node> iterator = list.iterator();
		while (iterator.hasNext()) {
			Node node = iterator.next();
			
			if (newNode.end < node.start) {
				newNode.print();
				node.print();
				while (iterator.hasNext()) iterator.next().print();
				return;
			}
			
			if (newNode.start > node.end) {
				node.print();
			}
			else {
				newNode.start = Math.min(newNode.start, node.start);
				newNode.end = Math.max(newNode.end, node.end);
			}
		}

		newNode.print();
	}
	
	private class Node {
		int start;
		int end;
		public Node(int start, int end) {
			this.start = start;
			this.end = end;
		}
		
		public void print() {
			System.out.println(this.start + ", " + this.end);
		}
	}

}
